package com.lzc.springcloud.user.application;

import com.lzc.springcloud.user.application.representation.UserRegisterRepresentation;
import com.lzc.springcloud.user.domain.identity.SysRoleEntity;
import com.lzc.springcloud.user.domain.identity.SysUserEntity;
import com.lzc.springcloud.user.infrastructure.persistence.SysUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Service
public class IdentityApplicationService {

    @Autowired
    private SysUserRepository sysUserRepository;

    @Transactional
    public void register(UserRegisterRepresentation user) {
        SysUserEntity sysUserEntity = user.toUser();
        sysUserEntity.assertPasswordsSame(user.password(), user.confirmPassword());
        sysUserRepository.save(user.toUser());
    }

    public SysUserEntity sysUser(Long userId) {
        return this.sysUserRepository().getOne(userId);
    }

    public SysUserEntity sysUser(String username, String password) {
        SysUserEntity sysUser = this.sysUserRepository().findByUsername(username);
        Set<SysRoleEntity> roleEntities= sysUser.roleEntities();
        sysUser.login(password);
        System.out.println("用户认证成功！");
        return sysUser;
    }

    private SysUserRepository sysUserRepository() {
        return this.sysUserRepository;
    }


}
